package edu.uic.kott.fragments;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import edu.uic.keyoutcomestrackertool.R;
import edu.uic.kott.activities.TrackKeyOutcomes;
import edu.uic.kott.db.KottDataSource;
import edu.uic.kott.model.Compute;
import edu.uic.kott.model.Course;
import edu.uic.kott.model.StudySession;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TrackStudySessions extends Fragment {
	
	static TextView classStudySessionsOn;
	public static String studySessionsDate;
	
	Button studySessionsRefreshButton;
	
	private static TableLayout studySessionsQueryLayout;
	
	KottDataSource datasource;
	List<Course> studyList;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View track_study_sessions_view = inflater.inflate(R.layout.track_study_sessions, container, false);
		
		classStudySessionsOn = (TextView) track_study_sessions_view.findViewById(R.id.classStudySessionsOn);
		classStudySessionsOn.setText(TrackKeyOutcomes.activeDate);
		
		studySessionsRefreshButton = (Button) track_study_sessions_view.findViewById(R.id.studySessionsRefresh);
		studySessionsRefreshButton.setOnClickListener(studySessionsRefreshListener);
		
		studySessionsQueryLayout = (TableLayout) track_study_sessions_view.findViewById(R.id.studySessionsQueryLayout);
		
		TrackKeyOutcomes.studySessionsVisible = true;
		TrackKeyOutcomes.UpdateVariables();
		
		StudySessionsData();
		
		return track_study_sessions_view;
	}
	
	public OnClickListener studySessionsRefreshListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			removeAllViews();
			StudySessionsData();
		}
		
	};
	
	public static void removeAllViews() {
		studySessionsQueryLayout.removeAllViews();
	}
	
	public void StudySessionsData() {
		datasource = new KottDataSource(this.getActivity());
		
		Course c = new Course();
		
		List<String> courseIds = new ArrayList<String>();
		
		List<Course> query = datasource.findAllCourses("trackStudySessions");
		
		for (Course course: query) {
			
			long courseId = course.getCourseId();
			
			String id = String.valueOf(courseId);
			
			courseIds.add(id);
		}
			
		for (String id : courseIds) {
			
			c = datasource.getCourseDetails(id);
			
			String courseName = c.getCourseName();
			String targetedWSS = c.getTargetedWSS();
			String sDate = c.getStartDate();
			String eDate = c.getEndDate();
			
			String completedSS = datasource.retreiveStudySessions(id, studySessionsDate);
			
			int index = Integer.parseInt(id) - 1;
			
			//Start and end dates are in MM/dd/yy
			DateFormat dfyy = new SimpleDateFormat("MM/dd/yy", Locale.US);
			DateFormat df = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
			
			Log.i("KOTT", sDate);
			
			Date start = null;
			try {
				start = dfyy.parse(sDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			Date end = null;
			try {
				end = dfyy.parse(eDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			Date active = null;
			try {
				active = df.parse(studySessionsDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			Log.i("KOTT", df.format(start));
			
			
			
			if (active.compareTo(start) >= 0 & active.compareTo(end) <= 0) {
				
				makeStudySessionsGUI(id, courseName, targetedWSS, completedSS, index);
			}
		}
		
		//Above should end up looping like this
		//makeStudySessionsGUI(0, "Math", "6", 0);
		//makeStudySessionsGUI(1, "Science", "6", 1);
		
	}


	public static void StudySessionsUpdateOnDateChange() {
		studySessionsDate = TrackKeyOutcomes.activeDate;
		classStudySessionsOn.setText("on: " + studySessionsDate);
		removeAllViews();
	}

	@Override
	public void onStop() {
		TrackKeyOutcomes.studySessionsVisible = false;
		super.onStop();
	}
	
	@Override
	public void onResume() {
		TrackKeyOutcomes.studySessionsVisible = true;
		super.onResume();
	}
	
	public void makeStudySessionsGUI(String classId, String className, String targetedWSS, String completedSS, int index) {
		LayoutInflater inflater = (LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	
		View newRowView = inflater.inflate(R.layout.study_sessions_group_view, null);
		
		TextView classText = (TextView) newRowView.findViewById(R.id.studySessionsClassName);
		classText.setText(className);
		
		TextView targetText = (TextView) newRowView.findViewById(R.id.studySessionsTargeted);
		targetText.setText(getResources().getString(R.string.targetedWeeklyStudySessions) + " " + targetedWSS);
		
		int completed = Integer.parseInt(completedSS);
		
		EditText completedEditText = (EditText) newRowView.findViewById(R.id.studySessionsCompleted);
		if (completed > 0) {
			completedEditText.setHint(completedSS);
			completedEditText.setFocusable(false);
		}
		
		
		Button submitButton = (Button) newRowView.findViewById(R.id.studySessionsSubmit);
		if (completed > 0) {
			Log.i("BUTTON", "is not clickable");
			submitButton.setVisibility(View.GONE);
			submitButton.setFocusable(false);
			submitButton.setClickable(false);
		}
		else {
			submitButton.setOnClickListener(submitListener);
		}
		
		
		TextView weekToDate = (TextView) newRowView.findViewById(R.id.studySessionsWeekToDate);
		weekToDate.setText(getResources().getString(R.string.weekToDateCompletedStudySessions) + " " + WeekToDateSS(classId, targetedWSS));
	
		TextView termToDate = (TextView) newRowView.findViewById(R.id.studySessionsTermToDate);
		termToDate.setText(getResources().getString(R.string.termToDateCompletedStudySessions) + " " + TermToDateSS(classId, targetedWSS));
	
		newRowView.setTag(classId);
		
		studySessionsQueryLayout.addView(newRowView, index);
	}
	
	private String TermToDateSS(String classId, String wTSS) {

		Compute compute = new Compute();
		
		String count = null;
		try{
			count = datasource.retreiveStudySessions(classId, studySessionsDate);
		}
		catch (Exception e){
			//Does not exist
		}
		
		double completed;
		
		Log.i("Count", "Count is = " + count);
		
		if (count != null) {
			completed = Double.parseDouble(count);
		}
		
		Course course = new Course();
		
		course = datasource.getCourseDetails(classId);
		String sDate = course.getStartDate();
		
		double weeks = compute.currentWeekMinusStartWeek(sDate, studySessionsDate);
		
		double target = Double.parseDouble(wTSS);
		double targeted = target * weeks;
		
		Log.i("Target", String.valueOf(targeted));
		
		completed = 0;
		completed = compute.sumCountList(datasource.retreiveTotalTermStudySessions(classId));
		
		double calculation = completed/targeted;
		
		String percentage = new DecimalFormat("#.#%").format(calculation);
		
		return percentage;
	}


	private String WeekToDateSS(String classId, String wTSS) {
		
		Compute compute = new Compute();
		List<String> weekDates = compute.datesInWeek(studySessionsDate);
		List<Integer> totalCount = new ArrayList<Integer>();
		
		for (String date: weekDates) {
			String count = datasource.retreiveStudySessions(classId, date);
			int countInt = Integer.parseInt(count);
			
			totalCount.add(countInt);
		}
		
		double targeted = Double.parseDouble(wTSS);
		double completed = compute.sumCountList(totalCount);
		
		double calculation = completed/targeted;
		
		Log.i("Calculation", String.valueOf(calculation));
		
		String percentage = new DecimalFormat("#.#%").format(calculation);
		
		return percentage;
	}

	public OnClickListener submitListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			//Get the group from table row parent, and view parent
			LinearLayout group = (LinearLayout) v.getParent().getParent();
			
			//Tags use classIds
			String classId = String.valueOf(group.getTag());
			
			//Get group Edit Text and text entered as integer
			EditText completedEntered = (EditText) group.findViewById(R.id.studySessionsCompleted);
			
			int completedText = completedEntered.getText().length();
			int count = 0;
			
			if (completedText > 0) {
				count = Integer.parseInt(completedEntered.getText().toString());
			}
			
			if (count > 0) {
				datasource.insertStudySessions(classId, studySessionsDate, count);
			}
			else {
				Toast.makeText(getActivity().getBaseContext(), "Enter an amount > 0", Toast.LENGTH_SHORT).show();
			}
			
			completedEntered.setFocusable(false);
			
			Log.i("KOTT", count + " sessions completed with class Id: " + classId + " on " + studySessionsDate);
		}
		
	};
	
	public OnFocusChangeListener completedFocusListener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			
			//If user has left edit text
			if (!hasFocus) {
				//Get the group and tag & class id
				LinearLayout group = (LinearLayout) v.getParent().getParent();
				String classId = String.valueOf(group.getTag());
				
				//Get the edit text and text
				EditText completedEntered = (EditText) group.findViewById(R.id.studySessionsCompleted);
				String completed = completedEntered.getText().toString();
				
				completedEntered.setHint(completed);
				
				Log.i("Completed", completed + " sessions completed today for class id: " + classId);
				
			}
			
		}

		
	};
}
